var saveSelectColor = {
    'Name': 'SelcetColor',
    'Color': 'theme-white'
}
$.ajaxSetup({
    headers: {
        'X-Xsrftoken': $('meta[name="csrf-token"]').attr('content')
    }
});
var defErpTypeid = 10;  //默认类别ID
var defErpTypeidEvent = function () {
};
var manageDepartment = null;

$(function () {
    // 判断用户是否已有自己选择的模板风格
    if (storageLoad('SelcetColor')) {
        $('body').attr('class', storageLoad('SelcetColor').Color)
    } else {
        storageSave(saveSelectColor);
        $('body').attr('class', 'theme-white')
    }

    autoLeftNav();
    $(window).resize(function () {
        autoLeftNav();
    });

    var $fullText = $('.admin-fullText');
    $('#admin-fullscreen').on('click', function () {
        $.AMUI.fullscreen.toggle();
    });
    $(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
        $fullText.text($.AMUI.fullscreen.isFullscreen ? '退出全屏' : '开启全屏');
    });

    wbs.init();
    pageScroll();
    $(window).resize(function () {
        pageScroll();
    });
});

// 本地缓存
function storageSave(objectData) {
    localStorage.setItem(objectData.Name, JSON.stringify(objectData));
}

function storageLoad(objectName) {
    if (localStorage.getItem(objectName)) {
        return JSON.parse(localStorage.getItem(objectName))
    } else {
        return false
    }
}


function checkQueryTableData(oData) {
    var queryData = new Object;
    $(oData).each(function (index, element) {
        if (element.name == "sEcho") {
            queryData[element.name] = element.value
        } else if (element.name == 'iDisplayStart') {
            queryData['offset'] = element.value
        } else if (element.name == 'iDisplayLength') {
            queryData['limit'] = element.value
        }
    });
    return queryData
}

// 风格切换
$('.tpl-skiner-toggle').on('click', function () {
    $('.tpl-skiner').toggleClass('active');
});

$('.tpl-skiner-content-bar').find('span').on('click', function () {
    $('body').attr('class', $(this).attr('data-color'))
    saveSelectColor.Color = $(this).attr('data-color');
    // 保存选择项
    storageSave(saveSelectColor);

});

// 侧边菜单开关
function autoLeftNav() {

    return false;
    $('.tpl-header-switch-button').on('click', function () {
        if ($('.left-sidebar').is('.active')) {
            if ($(window).width() > 1024) {
                $('.tpl-content-wrapper').removeClass('active');
            }
            $('.left-sidebar').removeClass('active');
            $('.tpl-header-margin-left').addClass('on');
        } else {
            $('.tpl-header-margin-left').removeClass('on');
            $('.left-sidebar').addClass('active');
            if ($(window).width() > 1024) {
                $('.tpl-content-wrapper').addClass('active');
            }
        }
    })

    if ($(window).width() < 1024) {
        $('.left-sidebar').addClass('active');
        $('.tpl-header-margin-left').removeClass('on');
    } else {
        $('.left-sidebar').removeClass('active');
        $('.tpl-header-margin-left').addClass('on');
    }
}

var wbs = function () {
    //初始化    
    function init() {
        if ($('.erptypeid').length > 0) {
            $('.erptypeid[data-id="' + defErpTypeid + '"]').removeClass("am-btn-default").addClass("am-btn-primary");
            $('.erptypeid').click(function () {
                $('.erptypeid').removeClass("am-btn-primary").addClass("am-btn-default");
                $(this).addClass("am-btn-primary");
                defErpTypeidEvent(this);
            });
        }
    }

    //菜单初化
    function pageSidebarInit(options) {
        var url = options.url;
        $.post(url, {}, function (re) {
            if (re.code === 0) {
                var $pageSidebar = $(options.slideBarBox);
                if ($pageSidebar.length === 0) {
                    return;
                }
                $pageSidebar.html('');

                var data = re.data;
                var html = [];
                var html2 = [];
                $(data).filter(function (i, e) {
                    //找出要节点
                    return e.Parent.Id === 0;
                }).each(function (i, cur) {
                    //菜单
                    if (cur.Rtype == 1) {
                        html.push('<li class="sidebar-nav-link">');
                        html.push('<a href="javascript:;" class="sidebar-nav-sub-title"  data-toid="' + cur.Id + '" title="' + cur.Name + '">');
                        html.push('<i class="' + getIcon(cur.Icon) + ' sidebar-nav-link-logo"></i>');
                        html.push('</a>');
                        html.push('</li>');
                        html2.push(showSiderBarSon(cur.Id, data));
                    }
                });
                if (html2.length > 0) {
                    $('#sidebarSubBox').append(html2.join('')); //设置子节点
                }
                $pageSidebar.html(html.join(''));
                $('.sidebar-nav-sub-title').click(function (e) {
                    var id = $(this).data('toid');
                    $('.appmenu-submenu-content').hide();
                    $('#appmenu-submenu-content-' + id).show();
                    $('#sidebar-title-value').html($(this).attr('title'));
                    showPinbtn(false);
                });
                //acitve 将href值与cur对应上的菜单激活
                var curli = $('dd a[href="' + options.cur + '"]');
                if (curli.length > 0) {
                    //激活当前
                    curli.addClass('active');
                    var id = curli.data('pid');
                    $('#appmenu-submenu-content-' + id).show();
                    $('.sidebar-nav-link [data-toid="' + id + '"]').addClass('active');
                    $('#sidebar-title-value').html($('.sidebar-nav-link [data-toid="' + id + '"]').attr('title'));
                }
            } else {
                layer.alert("获取失败", {icon: 2, title: "失败"})
            }

        }, 'json');

        $('.siderbar-appmenu-submenu-pinbtn').click(function () {
            showPinbtn(true);
        });

    }

    function showPinbtn(ishide) {
        if (ishide) {
            $('#sidebarSubBox').hide();
            $('.tpl-content-wrapper').css({'margin-left': '45px'});
        } else {
            $('#sidebarSubBox').show();
            $('.tpl-content-wrapper').css({'margin-left': '245px'});
        }
    }

    function showSiderBarSon(id, data) {
        var html = [];
        html.push('<div class="appmenu-submenu-content" style="display:none" id="appmenu-submenu-content-' + id + '"><div class="appmenu-set-slimscroll">');
        $(data).filter(function (i1, e1) {
            return e1.Parent.Id === id;
        }).each(function (i2, e2) {
            //递归调用，显示子节点
            if (e2.Rtype == 0) {
                html.push('<dt><span>' + e2.Name + '</span></dt>');
            } else if (e2.Rtype == 1) {
                html.push('<dd><a href="' + e2.LinkUrl + '" data-pid="' + id + '">' + e2.Name + '</a></dd>');
            }

            $(data).filter(function (i3, e3) {
                return e3.Parent.Id === e2.Id;
            }).each(function (i4, e4) {
                if (e4.Rtype == 1) {
                    html.push('<dd><a href="' + e4.LinkUrl + '" data-pid="' + id + '">' + e4.Name + '</a></dd>');
                }
            });

        });
        html.push('</div></div>');
        return html.join('');
    }

    function getIcon(icon) {
        if (!icon || icon.length === 0) {
            return "fa fa-circle-o"
        }
        return icon;
    }

    return {
        init: init,
        //页面左侧菜单初始化
        pageSidebarInit: pageSidebarInit
    }
}();

function pageScroll() {
    var windowHeight = $(window).height();
    var headerHeader = $('header').height();
    var heights = windowHeight - headerHeader;
    $('#mainPageContent').slimscroll({
        height: heights,
        width: '100%',
        alwaysVisible: true,
    });
    $('#pageSidebar').slimscroll({
        height: heights - 50,
        size: "4px",
        color: '#0e90d2',
        alwaysVisible: true,
    });
    //设置子菜单滚动事件
    $('.appmenu-set-slimscroll').slimscroll({
        height: heights,
        color: '#0e90d2',
        alwaysVisible: true,
    });

}

//formDoSubmit为公共提交页面

$("#formDoSubmit,#formDoSubmitTwo").validator({
    submit: function (t) {
        if (this.isFormValid()) {
            var that = $('#' + t.currentTarget.id);
            var submitBtn = that.find('button[type="submit"]');
            if (submitBtn.hasClass('am-disabled')) {
                return false;
            }
            submitBtn.addClass('am-disabled');

            $.ajax({
                url: that.attr("action")
                , type: 'post'
                , data: that.serialize()
                , dataType: 'json'
                , success: function (response) {
                    layer.msg(response.msg);
                    if (response.code === 0) {
                        setTimeout(function () {
                            submitBtn.removeClass('am-disabled');
                            that.attr('reback') ? location.href = that.attr('reback') : '';
                        }, 1000);
                    } else {
                        submitBtn.removeClass('am-disabled');
                    }
                }
                , error: function (error) {
                    submitBtn.removeClass('am-disabled');
                    layer.msg('数据提交失败！');
                }
            });
        }
        return false;
    }
});

$("#formDoSubmitDialog").validator({
    submit: function () {
        if (this.isFormValid()) {
            var that = $("#formDoSubmitDialog");
            var submitBtn = that.find('button[type="submit"]');
            if (submitBtn.hasClass('am-disabled')) {
                return false;
            }
            submitBtn.addClass('am-disabled');
            $.ajax({
                url: that.attr("action")
                , type: 'post'
                , data: that.serialize()
                , dataType: 'json'
                , success: function (response) {
                    layer.msg(response.msg);
                    if (response.code === 0) {
                        setTimeout(function () {
                            submitBtn.removeClass('am-disabled');
                            if (typeof parent.dialogReback == 'function') {
                                parent.dialogReback();
                            }
                            parent.layer.closeAll('iframe');
                        }, 1000);
                    } else {
                        submitBtn.removeClass('am-disabled');
                    }
                }
                , error: function (error) {
                    submitBtn.removeClass('am-disabled');
                    layer.msg('数据提交失败！');
                }
            });
        }
        return false;
    }
});

function timetrans(date) {
    var date = new Date(date * 1000);//如果date为10位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}

function timetransDate(date) {
    var date = new Date(date * 1000);//如果date为10位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return Y + M + D;
}

//产品类型名称
function productTypeidName(tid) {
    var typeid = {10: "光学镜片", 20: "隐形眼镜", 30: "光学镜架", 40: "成品镜", 41: "太阳镜", 50: "护理产品", 60: "辅料其它", 70: "药品"};
    var n = typeid[tid];
    if (!n) {
        return '';
    }
    return n;
}

//产品组合名称
function productGroupName(datas) {
    var name = '';
    var data = {};
    var gName = '';
    data = datas;
    if (data.BrandName != data.Name) {
        gName = data.BrandName + data.Name;
    } else {
        gName = data.Name;
    }
    switch (data.TypeId) {
        case 10:
            name = gName + data.Refractivity + data.Genre + data.OpticalDesign;
            break;
        case 20:
            name = gName + data.CastAway + data.Spec + data.ColourNumber;
            break;
        case 30:
            name = gName + data.MaterialQuality;
            break;
        case 40:
            name = gName + data.ModelNumber + data.ColourNumber + data.Genre;
            break;
        case 41:
            name = gName;
            break;
        case 50:
            name = gName + data.Spec;
            break;
        case 70:
            name = gName + data.Spec;
            break;
        default:
            name = gName;
            break;
    }
    return name;
}

/** 数字金额大写转换(可以处理整数,小数,负数) */
function smalltoBIG(n) {
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }

        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;

    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零');
}

/**日期转换成数组**/
function dateToArray(date) {
    if (date == '') {
        return false;
    }
    var d = new Object;
    s = date.split('-');
    d.y = s[0] || '';
    d.m = s[1] || '';
    d.d = s[2] || '';
    return d
}

//判断是否需要弹出度数选择框
function checkIsSetGlassesNumber(typeid) {
    if (typeid <= 30) {  //需要弹出
        return true;
    }
    return false

}

function formValidatorReset(id) {
    $("#" + id).validator('destroy');
    $('#' + id).validator({validateOnSubmit: true});
}

//处理金额小数位
function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

function formatnumber(srcstr, nafterdot) {
    nafterdot = nafterdot || "#,##0.00";
    // TODO: 将format中的自定义字符换掉
    if (srcstr == "" || srcstr == undefined || srcstr == null || srcstr == "0") {
        return srcstr;
    }
    var v = format(nafterdot, srcstr);
    return v;
}

$.fn.extend({
    'serializeObject': function () {
        var a, o, h, i, e;
        a = this.serializeArray();
        o = {};
        h = o.hasOwnProperty;
        for (i = 0; i < a.length; i++) {
            e = a[i];
            if (!h.call(o, e.name)) {
                o[e.name] = e.value;
            }
        }
        return o;
    }
});

document.onkeydown = function () {

};

//获取管理的部门
var get_department_url = '/department/manage/list';

function get_manage_departments(callback) {
    if (manageDepartment == null) {
        $.post(get_department_url, function (res) {
            manageDepartment = res.data;
            callback(manageDepartment);
        }, 'json');
    } else {
        callback(manageDepartment);
    }
}

//获取URL参数
function getQueryValue(queryName) {
    var query = decodeURI(window.location.search.substring(1));
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == queryName) {
            return pair[1];
        }
    }
    return null;
}

//参数值不为空时，存在参数则更新，否则不操作
function updateQueryStringParameter(uri, key, value) {
    if (!value) {
        return uri;
    }
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        return uri + separator + key + "=" + value;
    }
}

//显示input查询建议
var inputQueryflag = false; //判断弹窗是否开启
function showInputQueryList(target) {
    var obj_offset = target.offset();
    var obj_height = target.height();
    var uri = target.data('uri');
    var w_width = target.data('width');
    var w_height = target.data('height');
    var kwd = target.val();
    var query_type = target.data('type');
    if(inputQueryflag == true) {  //防止重复弹出
        return false;
    }
    if (kwd == '') {
        layer.msg('请填写关键字');
        return false;
    }

    layer.open({
        type: 2,
        title: false,
        shade: 0.1,
        scrollbar:false,
        shadeClose: true,
        offset: [(obj_offset.top + obj_height + 15) + 'px', obj_offset.left + 'px'],
        area: [w_width + 'px', w_height + 'px'],
        content: uri + '?kwd=' + kwd+'&query_type='+query_type,
        end:function () {
            inputQueryflag = false;
        }
    });
    inputQueryflag = true;
}
//关闭输入弹窗
function closeInputQueryList(index) {
    if(!index) {
        index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    }
    parent.layer.close(index); //再执行关闭
    inputQueryflag = false;
}

//绑定对象回车事件
function setEnterEvevtToObject(target_id, callback) {
    $('#'+target_id).keypress(function(event){
        var keynum = (event.keyCode ? event.keyCode : event.which);
        if(keynum == '13'){
            callback($(this))
        }
    });
}
//获取地址栏信息
function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}
//输入用法,途径、频次、天数
function showUsageFormat(tj, pc, ts) {
    if(tj) {
        return tj+'，'+pc+' / '+ts+'天';
    } else {
        return pc;
    }

}
